package cn.com.controller;

import cn.com.Util.CopyUtils;
import cn.com.domain.DocumentEntity;
import cn.com.domain.dto.DocumentDTO;
import cn.com.mapper.DocumentMapper;
import cn.com.response.BaseResponse;
import cn.com.response.BaseResponseStatus;
import cn.com.service.DocumentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 公文管理
 *
 * @Author CRL
 * @Date 2021/4/27 21:22
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/document")
public class DocumentController {

    @Autowired
    DocumentService documentService;

    @Autowired
    DocumentMapper documentMapper;

    @PostMapping
    public BaseResponse<DocumentEntity> creat(@RequestBody(required = false) DocumentDTO requestDto) {
        return documentService.saveDocument(requestDto);
    }

    @DeleteMapping("/{id}")
    public BaseResponse delete(@PathVariable("id") String id) {
        int i = documentMapper.deleteById(id);
        if (i == 1) {
            return new BaseResponse(BaseResponseStatus.OK, "删除成功");
        } else {
            return new BaseResponse<>(BaseResponseStatus.FAILURE, "删除失败");
        }
    }

    @PutMapping("/{id}")
    public BaseResponse update(@PathVariable("id") String id, @RequestBody(required = false) DocumentDTO requestDto) {
        DocumentEntity serviceById = documentService.getById(id);
        CopyUtils.copyProperties(requestDto, serviceById);
        boolean b = documentService.saveOrUpdate(serviceById);
        if (b) {
            return new BaseResponse<>(requestDto);
        } else {
            return new BaseResponse<>(BaseResponseStatus.FAILURE, "更新失败");
        }
    }

    @PostMapping("/query")
    public BaseResponse query(@RequestBody(required = false) DocumentDTO requestDto) {
        Integer pageNo = requestDto.getPageNo();
        Integer pageSize = requestDto.getPageSize();
        IPage<DocumentEntity> userPage = new Page<>(pageNo, pageSize);
        QueryWrapper<DocumentEntity> wrapper = new QueryWrapper<>();
        CopyUtils.copyProperties(requestDto, wrapper);
        IPage<DocumentEntity> backlogEntityIPage = documentMapper.selectPage(userPage, wrapper);
        return new BaseResponse(backlogEntityIPage);
    }

    @GetMapping("/{id}")
    public BaseResponse findOneById(@PathVariable("id") String id) {
        DocumentEntity serviceById = documentService.getById(id);
        return new BaseResponse(serviceById);
    }

    @GetMapping("/decode/{id}")
    public BaseResponse findById(@PathVariable("id") String id) {
        return documentService.findById(id);
    }


}
